package com.onpositive.notes.android.ui.elements;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import com.onpositive.businessdroids.model.IColumn;
import com.onpositive.businessdroids.model.IField;
import com.onpositive.businessdroids.model.IModelChangeListener;
import com.onpositive.businessdroids.model.TableModel;
import com.onpositive.businessdroids.model.aggregation.IAggregator;
import com.onpositive.businessdroids.model.impl.AbstractCollectionBasedModel;
import com.onpositive.businessdroids.model.impl.AbstractComputableField;
import com.onpositive.businessdroids.ui.IOpenListener;
import com.onpositive.businessdroids.ui.IViewer;
import com.onpositive.businessdroids.ui.actions.ActionContribution;
import com.onpositive.businessdroids.ui.actions.IContributionItem;
import com.onpositive.businessdroids.ui.actions.IContributionItemProvider;
import com.onpositive.businessdroids.ui.dataview.DataViewFactory;
import com.onpositive.businessdroids.ui.dataview.StructuredDataView;
import com.onpositive.businessdroids.ui.dataview.renderers.IFieldRenderer;
import com.onpositive.notes.android.main.CommonResources;
import com.onpositive.notes.android.main.EditNoteActivity;
import com.onpositive.notes.android.main.NotesActivity;
import com.onpositive.notes.android.tools.NoteRecordRenderer;
import com.onpositive.notes.android.tools.SpaceTokenizer;
import com.onpositive.notes.android.tools.TextColorProvider;
import com.onpositive.notes.model.INote;
import com.onpositive.notes.parser.BasicNoteParser;
import com.onpositive.notes.services.BasicNoteRegistry;
import com.onpositive.notes.services.TemplateModelRegistry;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.MultiAutoCompleteTextView;

public class NotesUI {
	
	private static String[] STRING_REALM = null;
	
	private MultiAutoCompleteTextView txt ;	
	private StructuredDataView sdv;
	private INote selectedNote ;
	
	View createView( Context context ){
		
		initTextView(context) ;
		
		LinearLayout lt = new LinearLayout( context ) ;
		lt.setOrientation( LinearLayout.VERTICAL ) ;
		
//		addButtons( context, lt ) ;
		return lt ;
	}
	
	public void initTextView( Context context ) {
		
		ArrayAdapter<String> adapter = new ArrayAdapter<String>( context,
                android.R.layout.simple_dropdown_item_1line, STRING_REALM);
		txt = new MultiAutoCompleteTextView(context) ;
        txt.setTokenizer( new SpaceTokenizer() );
        txt.setAdapter(adapter) ;
        txt.addTextChangedListener( new TextColorProvider(txt) ) ;
	}

	private void addButtons(Context context, LinearLayout lt2) {
		
		LinearLayout lt = new LinearLayout(context) ;
		lt.setOrientation(LinearLayout.HORIZONTAL) ;
		
		Button deleteButton = new Button(context) ;
		deleteButton.setText("DELETE") ;		
		deleteButton.setWidth(150) ;
		lt.addView(deleteButton,new LayoutParams( LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)) ;
		
		Button okButton = new Button(context) ;
		okButton.setText( "OK" ) ;
		okButton.setWidth(150) ;
		lt.addView(okButton,new LayoutParams( LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)) ;

		Button cancelButton = new Button(context) ;
		cancelButton.setText("CANCEL") ;		
		cancelButton.setWidth(150) ;
		lt.addView(cancelButton,new LayoutParams( LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)) ;
		
		
		
//		deleteButton.setOnClickListener( new View.OnClickListener() {
//			
//			@Override
//			public void onClick(View v) {
//				
//				txt.setText("") ;
//				if( selectedNote != null )
//					BasicNoteRegistry.getInstance().unRegisterNote(selectedNote) ;
//				newNote = new BasicNoteParser().parse( txt.getText().toString() ) ;
//				delete = true ;
//				EditNoteActivity.this.finish() ;				
//			}
//		}) ;
//		
//		okButton.setOnClickListener( new View.OnClickListener() {
//			
//			@Override
//			public void onClick(View v) {
//				INote note = new BasicNoteParser().parse( txt.getText().toString() ) ;
//				BasicNoteRegistry.getInstance().registerNote(note) ;
//				
//			}
//		}) ;
//
//		cancelButton.setOnClickListener( new View.OnClickListener() {
//			
//			@Override
//			public void onClick(View v) {
//				EditNoteActivity.this.finish() ;				
//			}
//		}) ;
		
		lt2.addView(lt) ;
	}
	
	public void initDataView( Context context, LinearLayout lt )
	{
		IField contentField = new AbstractComputableField() {

			@Override
			public Object getPropertyValue(Object object) {

				if (object == null)
					return "NULL";

				if (object instanceof INote)
					return ((INote) object).getInitialText() ;

				return object.toString();
			}
		};

		IField dateField = new AbstractComputableField() {

			@Override
			public Object getPropertyValue(Object object) {

				if (object == null)
					return "NULL";

				if (object instanceof INote) {
					Date date = ((INote) object).getDate();
					SimpleDateFormat sdf =
							new SimpleDateFormat( "dd,MMMM,yyyy", CommonResources.defaultLocale ) ;
					
					String result = sdf.format(date);
					return result;
				}
				return object.toString();
			}
		};
		
		IField[] fields = new IField[]{ contentField , dateField } ;
		
		sdv = DataViewFactory.createTable(
				context, BasicNoteRegistry.getInstance().getAllNotes(), null, null, fields);
		
		sdv.setActionBarVisible(true) ;
		sdv.setHeaderVisible(true) ;
		sdv.setFooterVisible(true) ;

		sdv.setOpenListener(new IOpenListener() {

			@Override
			public void openElement(View parent, View elementView, Object element, int pos)
			{
				INote note = (INote) element;
				selectedNote = note ;
				txt.setText( note.getText() ) ;
			}
		});
		sdv.getTableModel().addModelChangeListener( new IModelChangeListener() {
			
			@Override
			public void aggregatorChanged(IAggregator oldAggregator,
					IAggregator newAggregator, IColumn column) {}
			
			@Override
			public void modelChanged(TableModel model) {
				Collection<Object> content = ((AbstractCollectionBasedModel)sdv.getTableModel()).getContent();
				HashSet<Integer> presentNotes = new HashSet<Integer>() ;
				for( Object obj : content ){
					INote note = (INote) obj ;
					if( note.getId() < 0 )
						BasicNoteRegistry.getInstance().registerNote(note) ;
					
					presentNotes.add( note.getId() ) ;
				}
				
				List<INote> allNotes = BasicNoteRegistry.getInstance().getAllNotes();
				
				ArrayList<INote> toDelete = new ArrayList<INote>() ;				
				for( INote note : allNotes ){
					if( !presentNotes.contains( note.getId() ) )
						toDelete.add(note) ;
				}
				for( INote note : toDelete )
					BasicNoteRegistry.getInstance().unRegisterNote(note) ;
			}
		}) ;
		
//		final Drawable icon = context.getResources().getDrawable( com.onpositive.notes.android.test.R.drawable.add) ;
//		sdv.setContributionItemProvider( new IContributionItemProvider() {
//			
//			ArrayList<IContributionItem> lst = new ArrayList<IContributionItem>(  Arrays.asList(
//					new IContributionItem[]{new ActionContribution( "Add new note", icon ) {
//						
//						@Override
//						protected void run() {
//							Intent intent = new Intent(NotesActivity.this, EditNoteActivity.class);
//							startActivityForResult(intent, REQUEST_EDIT_NOTE);				
//						}
//					}})) ;
//			
//			@Override
//			public List<IContributionItem> getContributionItemsFor(IColumn column) {
//				return lst;
//			}
//			
//			@Override
//			public List<IContributionItem> getCommonContributionItems() {
//				return lst;
//			}
//		}) ;
		
		sdv.getViewRendererService().registerClassRenderer( INote.class, new NoteRecordRenderer() ) ;
		
		lt.addView(sdv, new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT) ) ;
	}
	
    private void init() {
		if( STRING_REALM == null ){
		
			Set<String> allTemplateKeys = TemplateModelRegistry.getInstance().getAllTemplateKeys();
	        ArrayList<String> lst = new ArrayList<String>( allTemplateKeys ) ;
	        STRING_REALM = lst.toArray( new String[ lst.size() ] ) ;
		}
    }
}
